using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace ExtendedWebBrowser2
{
  [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1301:AvoidDuplicateAccelerators")]
  partial class MainForm : Form
  {
      private FormWindowState ws;
      
    public MainForm()
    {
      InitializeComponent();
      _windowManager = new WindowManager(this.tabControl);
      _windowManager.CommandStateChanged += new EventHandler<CommandStateEventArgs>(_windowManager_CommandStateChanged);
      _windowManager.StatusTextChanged += new EventHandler<TextChangedEventArgs>(_windowManager_StatusTextChanged);
      _windowManager.DocumentTitleChanged += new EventHandler<TextChangedEventArgs>(_windowManager_DocumentTitleChanged);
      _windowManager.InfoChanged += new EventHandler<TextChangedEventArgs>(_windowManager_InfoChanged);
    }

    // Update the status text
    void _windowManager_StatusTextChanged(object sender, TextChangedEventArgs e)
    {
      this.toolStripStatusLabel.Text = e.Text;
    }
    public static Image favicon(string u)
    {

        WebRequest re = WebRequest.Create(u);
        try
        {
            WebResponse rsp = re.GetResponse();

            Stream s = rsp.GetResponseStream();
            return Image.FromStream(s);
        }
        catch
        {
            return null;
        }
    }

    // Update the DocumentTitle
    void _windowManager_DocumentTitleChanged(object sender, TextChangedEventArgs e)
    {
        ExtendedWebBrowser brw = this._windowManager.ActiveBrowser;

        this.Text = "JXC version 1.0";
        if (this.tabControl.TabCount > 0 && e.Text != "")
        {
            this.Text = "Web";

            tabControl.SelectedTab.ImageIndex = 0;

            if (brw == null) return;
            if (brw.Url == null) return;

            string x,faviurl = null;
            int i, b, ed;
            if (brw.Url.AbsoluteUri.Contains("ju.taobao"))
            {
                this.Text = "JXC";
            }

            x = brw.DocumentText;
            if (x != null)
            {
                i = x.IndexOf("favicon");
                if (i >= 0)
                {
                    b = x.LastIndexOf('=', i);
                    ed = x.IndexOf('"', i);
                    if (b >= 0 && ed >= 0)
                    {
                        faviurl = x.Substring(b + 1, ed - (b + 1)).Trim('"');
                        if (!faviurl.StartsWith("http"))
                        {
                            faviurl = brw.Url.AbsoluteUri.TrimEnd('/') + "/" + faviurl.Trim('/');
                        }
                    }
                }
            }
            if (faviurl == null)
            {
                faviurl = brw.Url.AbsoluteUri.TrimEnd('/') + "/favicon.ico";
            }

            int idx = imageList1.Images.IndexOfKey(faviurl);
            if (idx == -1)
            {
                Image ico = favicon(faviurl);
                if (ico != null)
                {
                    imageList1.Images.Add(faviurl, ico);
                    tabControl.SelectedTab.ImageIndex = imageList1.Images.Count - 1;
                }
            }
            else
            {
                tabControl.SelectedTab.ImageIndex = idx;
            }
            //MessageBox.Show(x);

            this.Text += " - " + e.Text;
        }


        //this.Text = "JXC - " + e.Text;
    }
    // Update the Info
    void _windowManager_InfoChanged(object sender, TextChangedEventArgs e)
    {
        this.notifyIcon1.Text = e.Text;
    }

    // Enable / disable buttons
    void _windowManager_CommandStateChanged(object sender, CommandStateEventArgs e)
    {
    }


    #region Tools menu
    // Executed when the user clicks on Tools -> Options
    private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
    {
      using (OptionsForm of = new OptionsForm())
      {
        of.ShowDialog(this);
      }
    }
    // Tools -> Show script errors
    private void scriptErrorToolStripMenuItem_Click(object sender, EventArgs e)
    {
      ScriptErrorManager.Instance.ShowWindow();
    }

    #endregion

    #region File Menu

    // File -> Print
    private void printToolStripMenuItem_Click(object sender, EventArgs e)
    {
      Print();
    }

    // File -> Print Preview
    private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
    {
      PrintPreview();
    }

    // File -> Exit
    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
      this.Close();
    }

    // File -> Open URL
    private void openUrlToolStripMenuItem_Click(object sender, EventArgs e)
    {
      using (OpenUrlForm ouf = new OpenUrlForm())
      {
        if (ouf.ShowDialog() == DialogResult.OK)
        {
          ExtendedWebBrowser brw = _windowManager.New(false);
          brw.Navigate(ouf.Url);
        }
      }
    }

    // File -> Open File
    private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
    {
      using (OpenFileDialog ofd = new OpenFileDialog())
      {
        ofd.Filter = Properties.Resources.OpenFileDialogFilter;
        if (ofd.ShowDialog() == DialogResult.OK)
        {
          Uri url = new Uri(ofd.FileName);
          WindowManager.Open(url);
        }
      }
    }
    #endregion

    #region Help Menu
    
    // Executed when the user clicks on Help -> About
    private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
    {
      About();
    }

    /// <summary>
    /// Shows the AboutForm
    /// </summary>
    private void About()
    {
      using (AboutForm af = new AboutForm())
      {
        af.ShowDialog(this);
      }
    }

    #endregion


    /// <summary>
    /// The WindowManager class
    /// </summary>
    private WindowManager _windowManager;

    // This is handy when all the tabs are closed.
    private void tabControl_VisibleChanged(object sender, EventArgs e)
    {
      if (tabControl.Visible)
      {
        this.panel1.BackColor = SystemColors.Control;
      }
      else
        this.panel1.BackColor = SystemColors.AppWorkspace;
    }

    // Starting the app here...
    private void MainForm_Load(object sender, EventArgs e)
    {
      // Open a new browser window
      _windowManager.New();
      ws = WindowState;
      //this.ShowInTaskbar = false;
    }


    #region Printing & Print Preview
    private void Print()
    {
      ExtendedWebBrowser brw = _windowManager.ActiveBrowser;
      if (brw != null)
        brw.ShowPrintDialog();
    }

    private void PrintPreview()
    {
      ExtendedWebBrowser brw = _windowManager.ActiveBrowser;
      if (brw != null)
        brw.ShowPrintPreviewDialog();
    }
    #endregion

    #region Toolstrip buttons
    private void closeWindowToolStripButton_Click(object sender, EventArgs e)
    {
      this._windowManager.New();
    }

    private void closeToolStripButton_Click(object sender, EventArgs e)
    {
      this._windowManager.Close();
    }

    private void printToolStripButton_Click(object sender, EventArgs e)
    {
      Print();
    }

    private void printPreviewToolStripButton_Click(object sender, EventArgs e)
    {
      PrintPreview();
    }

    private void backToolStripButton_Click(object sender, EventArgs e)
    {
      if (_windowManager.ActiveBrowser != null && _windowManager.ActiveBrowser.CanGoBack)
        _windowManager.ActiveBrowser.GoBack();
    }

    private void forwardToolStripButton_Click(object sender, EventArgs e)
    {
      if (_windowManager.ActiveBrowser != null && _windowManager.ActiveBrowser.CanGoForward)
        _windowManager.ActiveBrowser.GoForward();
    }

    private void stopToolStripButton_Click(object sender, EventArgs e)
    {
      if (_windowManager.ActiveBrowser != null)
      {
        _windowManager.ActiveBrowser.Stop();
      }
    }

    private void refreshToolStripButton_Click(object sender, EventArgs e)
    {
      if (_windowManager.ActiveBrowser != null)
      {
        _windowManager.ActiveBrowser.Refresh(WebBrowserRefreshOption.Normal);
      }
    }

    private void homeToolStripButton_Click(object sender, EventArgs e)
    {
      if (_windowManager.ActiveBrowser != null)
        _windowManager.ActiveBrowser.GoHome();
    }

    private void searchToolStripButton_Click(object sender, EventArgs e)
    {
      if (_windowManager.ActiveBrowser != null)
        _windowManager.ActiveBrowser.GoSearch();
    }

    #endregion

   

    public WindowManager WindowManager
    {
      get { return _windowManager; }
    }


    private void tabControl_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            this._windowManager.Close();
        }
        else if (e.Button == MouseButtons.Left)
        {
            this._windowManager.New(false);
            this._windowManager.ActiveBrowser.Navigate("about:blank");
        }
    }

    private void toolStripMenuItem3_Click(object sender, EventArgs e)
    {
        this._windowManager.New();
    }

    private void toolStripMenuItem4_Click(object sender, EventArgs e)
    {
        this._windowManager.Close();
    }

    private void toolStripMenuItem5_Click(object sender, EventArgs e)
    {
        ExtendedWebBrowser brw = _windowManager.New(false);
        Uri url = new Uri("http://fee.ju.taobao.com/seller/aucItems.htm");

        brw.Navigate(url);

    }

    private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            this.Show();
            ShowInTaskbar = true;
            this.WindowState = ws;
            this.Activate();
        }
    }

    private void MainForm_Deactivate(object sender, EventArgs e)
    {
        if (WindowState == FormWindowState.Minimized)
        {
            ShowInTaskbar = false;
            Hide();
        }
    }

    private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            if (this.Visible)
                this.Hide();
        }
        else
        {
            if (this.Visible)
                this.Activate();
        }
    }

    private void tabControl_Selected(object sender, TabControlEventArgs e)
    {
        this.Text = "JXC version 1.0";
        if (this.tabControl.TabCount > 0 && this.tabControl.SelectedTab.Text != "")
        {
            this.Text = "Web";
            if (this._windowManager.ActiveBrowser != null && this._windowManager.ActiveBrowser.Url != null)
            {
                if (this._windowManager.ActiveBrowser.Url.AbsoluteUri.Contains("ju.taobao"))
                {
                    this.Text = "JXC";
                }
            }

            this.Text += " - " + this.tabControl.SelectedTab.Text;
        }
    }

    private void MainForm_ClientSizeChanged(object sender, EventArgs e)
    {
        if (this.WindowState != FormWindowState.Minimized)
            ws = WindowState;
    }

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (this.tabControl.TabCount > 0)
        {
            foreach (TabPage page in tabControl.TabPages)
            {
                if (page != null)
                {
                    BrowserControl bc = page.Tag as BrowserControl;
                    if (bc != null)
                    {
                        bc.SaveHtml();
                        bc.SaveLog();
                    }
                    // Remove the page
                    tabControl.TabPages.Remove(page);
                    // Dispose the page (controls on the page are also disposed this way)
                    page.Dispose();
                }
            }
        }
    }


  }
}